package com.study.controller;

import com.alibaba.fastjson.JSON;
import com.study.annotation.IgnoreResponseAdvice;
import com.study.service.IJWTService;
import com.study.vo.JwtToken;
import com.study.vo.UsernameAndPassword;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/authority")
public class AuthorityController {

    @Autowired
    private IJWTService ijwtService;

    /**
     * 从授权中心获取token
     * 并且返回信息中没有统一返回的包装
     * @param usernameAndPassword
     * @return
     * @throws Exception
     */
    @IgnoreResponseAdvice
    @PostMapping("/getToken")
    public JwtToken getToken(@RequestBody UsernameAndPassword usernameAndPassword) throws Exception {

        log.info("request to get token with param: [{}]",
                JSON.toJSONString(usernameAndPassword));

        return new JwtToken(ijwtService.generateToken(usernameAndPassword.getUsername(),
                usernameAndPassword.getPassword()));
    }

    /**
     * 注册用户
     * 并返回当前注册用户的token
     * @param usernameAndPassword
     * @return
     * @throws Exception
     */
    @IgnoreResponseAdvice
    @PostMapping("/register")
    public JwtToken register(@RequestBody UsernameAndPassword usernameAndPassword) throws Exception{

        log.info("register user with param: [{}]",JSON.toJSONString(usernameAndPassword));

        return new JwtToken(ijwtService.registerUserAndGenerateToken(usernameAndPassword));


    }


}
